package com.ua.open.authentication.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ua.common.model.SysModule;
import com.ua.common.model.SysUser;
import com.ua.open.authentication.persistence.SysUserMapper;
import com.ua.secure.module.persistence.ModuleMapper;


@Service
public class SysUserService {

  @Autowired
  private SysUserMapper sysUserMapper;
  
  @Autowired
  private ModuleMapper moduleMapper;

  /**
   * 根据用户名获取用户信息
   * @param username 用户名
   * @return
   */
  public SysUser getSysUser(String username) {
	  try {
		SysUser sysUser = sysUserMapper.getSysUserByLoginName(username);
		  if("sa".equals(username)){
			  sysUser.setSysModules(moduleMapper.getSysModules());
		  }
		  // 组装模块树
		  List<SysModule> modules = sysUser.getSysModules();
		  List<SysModule> moduleList = buildModuleTree(modules);
		  sysUser.setSysModules(moduleList);
		  return sysUser;
	} catch (Exception e) {
		System.out.println("------华丽丽的分隔线-----------------");
		e.printStackTrace();
	}
	return null;
  }
  
  private List<SysModule> buildModuleTree(List<SysModule> modules){
	  List<SysModule> roots = new ArrayList<SysModule>();
	  
	  Map<String,List<SysModule>> map = new HashMap<String,List<SysModule>>();
	  if(modules!=null && modules.size()>0){
		  for(SysModule m : modules){
			  String parentModuleId = m.getParentModuleId();
			  List<SysModule> children = map.get(parentModuleId);
			  if(children==null){
				  children = new ArrayList<SysModule>();
			  }
			  children.add(m);
			  map.put(parentModuleId, children);
			  if(parentModuleId==null || "0".equals(parentModuleId)){
				  roots.add(m);
			  }
		  }
		  recursion(roots,map);
	  }
	  return roots;
  }
  
  private void recursion(List<SysModule> childs,Map<String,List<SysModule>> map){
	  for(SysModule m : childs){
		  String parentModuleId = m.getModuleId();
		  List<SysModule> children = map.get(parentModuleId);
		  if(children==null)
			  return;
		  m.setChildren(children); 
		  recursion(children,map);
	  }
	  
  }
  
}
